package com.vegetable.modules.service.quotation.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.modules.entity.quotation.Quotation;
import com.vegetable.modules.entity.quotation.QuotationArea;
import com.vegetable.modules.entity.quotation.po.QuotationAreaAddPO;
import com.vegetable.modules.entity.quotation.po.QuotationQueryPO;
import com.vegetable.modules.mapper.quotation.QuotationAreaMapper;
import com.vegetable.modules.service.quotation.IQuotationAreaService;
import com.vegetable.modules.service.quotation.IQuotationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IQuotationAreaServiceImpl extends ServiceImpl<QuotationAreaMapper, QuotationArea>  implements IQuotationAreaService {
    @Resource
    private IQuotationService iQuotationService;
    @Override
    public List<QuotationArea> quotationAreaList(String areaNameLike, String mobile, Boolean isEmpty) {
        QueryWrapper<QuotationArea> wrapper = new QueryWrapper();
        wrapper.like(StringUtils.isNotBlank(areaNameLike), "area_name", areaNameLike);
        wrapper.like(StringUtils.isNotBlank(mobile), "commander_mobile", mobile);
        wrapper.gt(ObjectUtil.isNotNull(isEmpty), "goods_num", 0);
        List<QuotationArea> result = getBaseMapper().selectList(wrapper);
        QuotationQueryPO param = new QuotationQueryPO();
        param.setUpdateTime(new Date());
        // 当前的所有报价
        List<Quotation> todayQuotations = iQuotationService.quotationList(param);
        if(CollectionUtil.isNotEmpty(result) && CollectionUtil.isNotEmpty(todayQuotations)){
            for (QuotationArea area : result) {
                List<Quotation> quotations = todayQuotations.stream().filter(t -> t.getAreaId().equals(area.getId())).collect(Collectors.toList());
                area.setUpdateNum(quotations.size());
            }
        }
        return result;
    }

    @Override
    public QuotationArea quotationArea(String areaName) {
        QueryWrapper<QuotationArea> wrapper = new QueryWrapper();
        wrapper.eq(StringUtils.isNotBlank(areaName), "area_name", areaName);
        return getBaseMapper().selectOne(wrapper);
    }

    @Override
    public int add(QuotationAreaAddPO po) {
        String sign = RandomStringUtils.randomAlphanumeric(1);
        QuotationArea qa = new QuotationArea();
        BeanUtils.copyProperties(po, qa);
        qa.setAreaSign(sign);
        return getBaseMapper().insert(qa);
    }
}
